<template> 
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="displayName">
        <el-input
          v-model="queryParams.displayName"
          placeholder="请输入名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="叶子节点" prop="isLeafDefault">
        <el-input
          v-model="queryParams.isLeafDefault"
          placeholder="请输入叶子节点"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['sbtz:sbtype:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['sbtz:sbtype:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['sbtz:sbtype:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['sbtz:sbtype:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="sbtypeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="层级编码" align="left" prop="typeCode" />
      <el-table-column label="层级名称" align="left" prop="displayName" />
      
      <!-- <el-table-column label="叶子节点" align="center" prop="isLeafDefault" />
      <el-table-column label="0正常 1停用" align="center" prop="status" /> -->
      <el-table-column
          label="允许父类型"
          prop="parentNames" 
        >
          <template #default="{ row }">
            {{ row.parentNames || '-' }}
          </template>
        </el-table-column>

        <el-table-column
          label="允许子类型"
          prop="childNames" 
        >
          <template #default="{ row }">
            {{ row.childNames || '-' }}
          </template>
        </el-table-column>

      
      <el-table-column label="操作" align="center" width="400" class-name="small-padding fixed-width">
        <template #default="scope">
          
          <!-- 新增：绑定上一级 -->
          <el-button link type="success" icon="Link"
                    @click="openBindParent(scope.row)"
                    v-hasPermi="['sbtz:sbtype:bindParent']">绑定上一级</el-button>

          <!-- 新增：绑定下一级（可多选） -->
          <el-button link type="warning" icon="Link"
                    @click="openBindChildren(scope.row)"
                    v-hasPermi="['sbtz:sbtype:bindChildren']">绑定下一级</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['sbtz:sbtype:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['sbtz:sbtype:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备类型对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="sbtypeRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="设备编码" prop="typeCode">
          <el-input v-model="form.typeCode" placeholder="请输入编码" />
        </el-form-item>
        <el-form-item label="设备名称" prop="displayName">
          <el-input v-model="form.displayName" placeholder="请输入名称" />
        </el-form-item>         
        <el-form-item label="备注说明" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 绑定上一级 -->
<el-dialog v-model="bindParentVisible" title="绑定上一级" width="520px" :close-on-click-modal="false">
  <el-form label-width="96px">
    <el-form-item label="当前类型">
      <el-tag>{{ bindTarget?.displayName || bindTarget?.name }}（{{ bindTarget?.typeCode || bindTarget?.code || '—' }}）</el-tag>
    </el-form-item>
    <el-form-item label="选择上级">
      <el-select-v2
      v-model="childCodes"            
      :options="childrenOptions"
      multiple filterable clearable remote collapse-tags
      :remote-method="searchChildrenOptions"
      :loading="optLoadingChildren"
      placeholder="输入名称/编码搜索，可多选"
      style="width: 100%"
    />
    </el-form-item>
  </el-form>
  <template #footer>
    <el-button @click="bindParentVisible=false">取消</el-button>
    <el-button type="primary" @click="submitBindParent">确定</el-button>
  </template>
</el-dialog>

<!-- 绑定下一级（多选） -->
<el-dialog v-model="bindChildrenVisible" title="绑定下一级" width="720px" :close-on-click-modal="false">
  <el-form label-width="96px">
    <el-form-item label="当前类型">
      <el-tag>{{ bindTarget?.displayName || bindTarget?.name }}（{{ bindTarget?.typeCode || bindTarget?.code || '—' }}）</el-tag>
    </el-form-item>
    <el-form-item label="选择下级">
      <el-select-v2
        v-model="childCodes"            
        :options="childrenOptions"
        multiple filterable clearable remote collapse-tags
        :remote-method="searchChildrenOptions"
        :loading="optLoadingChildren"
        placeholder="输入名称/编码搜索，可多选"
        style="width: 100%"
      />
    </el-form-item>
  </el-form>
  
  <template #footer>
    <el-button @click="bindChildrenVisible=false">取消</el-button>
    <el-button type="primary" @click="submitBindChildren">确定</el-button>
  </template>
</el-dialog>




  </div>
</template>

<script setup name="Sbtype">
import { listSbtype, getSbtype, delSbtype, addSbtype, updateSbtype,apiBindChildren,apiBindParent } from "@/api/sbtz/sbtype";
import { ElMessage } from 'element-plus'

const { proxy } = getCurrentInstance();

const sbtypeList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    displayName: null,
    typeCode: null,
    isLeafDefault: null,
    status: null,
    remark: null
  },
  rules: {
    displayName: [
      { required: true, message: "设备名称不能为空", trigger: "blur" }
    ],
    typeCode: [
      { required: true, message: "设备编码不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询设备类型列表 */
function getList() {
  loading.value = true;
  listSbtype(queryParams.value).then(response => {
    sbtypeList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}
const bindParentVisible   = ref(false)
const bindChildrenVisible = ref(false)
 
const childCodes = ref([])         // ✅ 由原来的 childIds 改为 childCodes
const childrenOptions = ref([])
const optLoadingChildren = ref(false)
const bindTarget = ref([])   


async function searchChildrenOptions(keyword = '') {
  optLoadingChildren.value = true
  try {
    const res = await listSbtype({ keyword, pageNum: 1, pageSize: 100 })
    const rows = res?.rows ?? []
    childrenOptions.value = rows
      .filter(r => r.typeCode !== bindTarget.value?.typeCode)  // ✅ 自身不可选
      .map(toOption)
  } finally {
    optLoadingChildren.value = false
  }
} 

const toOption = (r) => ({
  value: r.typeCode, // ✅ 用 typeCode 做选值
  label: `${r.displayName ?? r.name ?? ''}${r.typeCode ? `(${r.typeCode})` : ''}`,
  raw: r,            // 保留原始行，必要时可拿到 id 等
})
 

function openBindParent(row) {
  bindTarget.value = row 
  bindParentVisible.value = true
  searchChildrenOptions('') // 首次拉一页
}

function openBindChildren(row) {
  bindTarget.value = row
  childCodes.value = []
  bindChildrenVisible.value = true
  searchChildrenOptions('')
}

async function submitBindChildren() {
  if (!bindTarget.value?.typeCode) return
  if (!childCodes.value?.length) {
    // 允许清空：如果你想“必须选至少一个”，把这段删掉并 return
    // ElMessage.warning('请先选择下级类型'); return
  }

  await apiBindChildren({
    parentType: bindTarget.value.typeCode,
    childTypes: childCodes.value, // 数组，可为空数组表示“清空子级”
  }) 

  ElMessage.success('绑定下一级成功')
  bindChildrenVisible.value = false
  typeof getList === 'function' && getList()
}

const loadingBind = ref(false);

async function submitBindParent() {
  // 现在：parentTypes=数组，childType=单个
  const parentTypes = Array.isArray(childCodes.value) ? childCodes.value : [];
  const childType   = bindTarget.value?.typeCode ?? null;

  if (!childType) {
    ElMessage.warning('请选择要绑定的【子类】');
    return;
  }

  // 如果允许“清空父级关系”，当 parentTypes 为空时给个确认
  if (parentTypes.length === 0) {
    const ok = await ElMessageBox.confirm(
      '不选择任何父类将清空该子类的父级绑定，确定继续？',
      '提示', { type: 'warning' }
    ).then(()=>true).catch(()=>false);
    if (!ok) return;
  }

  loadingBind.value = true;
  try { 
    await apiBindParent({ parentTypes, childType });
    ElMessage.success('已保存父子关系');
    // TODO：刷新列表 / 关闭弹窗
    await getList(); 
    bindParentVisible.value = false;
  } finally {
    loadingBind.value = false;
  }
}

 

// 表单重置
function reset() {
  form.value = {
    typeCode: null,
    displayName: null,
    icon: null,
    color: null,
    isLeafDefault: null,
    levelHint: null,
    status: null,
    remark: null
  };
  proxy.resetForm("sbtypeRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.typeCode);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加设备类型";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _typeCode = row.typeCode || ids.value
  getSbtype(_typeCode).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改设备类型";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["sbtypeRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateSbtype(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addSbtype(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _typeCodes = row.typeCode || ids.value;
  proxy.$modal.confirm('是否确认删除设备类型编号为"' + _typeCodes + '"的数据项？').then(function() {
    return delSbtype(_typeCodes);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('sbtz/sbtype/export', {
    ...queryParams.value
  }, `sbtype_${new Date().getTime()}.xlsx`)
}

getList();
</script>
